import { IListItem } from '@/utils/interfaces'
import { apiStore } from '@/utils/store/apiStore'
import {
    Button,
    Modal,
    Popover,
    Radio,
    Space,
    Table,
    Tooltip,
} from '@arco-design/web-react'
import { keyBy } from 'lodash-es'

// 处理函数
const combineHandlerMap = {
    // 直接覆盖
    overwrite: (oldItem: IListItem, newItem: IListItem) => {
        return newItem
    },
    // 保留现有的数据
    keep: (oldItem: IListItem, newItem: IListItem) => {
        return oldItem
    },
    // 更新现有的数据
    update: (oldItem: IListItem, newItem: IListItem) => {
        return {
            ...oldItem,
            ...newItem,
        }
    },
    // 保留原数据，更新新的数据
    updateNew: (oldItem: IListItem, newItem: IListItem) => {
        return {
            ...newItem,
            ...oldItem,
        }
    },
}

// 重复处理组件
export interface IDuplicateHandlerProps {
    // 全部列表的id映射
    allListIdMap: Record<string, IListItem>
    // 导入列表的id映射
    itemsIdMap: Record<string, IListItem>
    // 已经存在的id列表
    existInAllList: IListItem[]
    // 取消
    onCancel: () => void
    // 确认，返回处理后的完整的列表
    onConfirm: (items: IListItem[]) => void
}
const DuplicateHandler: React.FC<IDuplicateHandlerProps> = ({
    allListIdMap,
    itemsIdMap,
    existInAllList,
    onCancel,
    onConfirm,
}) => {
    // 处理方式
    const [combineTypeData, setCombineTypeData] = useState<
        Record<string, keyof typeof combineHandlerMap>
    >({})

    // 取消
    const handleCancel = () => {
        onCancel()
    }

    // 确认
    const handleConfirm = () => {
        const newItems = Object.values(itemsIdMap).map((item) => {
            const combineType = combineTypeData[item.id]
            if (combineType) {
                return combineHandlerMap[combineType](
                    allListIdMap[item.id],
                    item,
                )
            }
            return item
        })
        onConfirm(newItems)
    }

    // 获取记录处理对象
    const getIdToHandlerMap = (handleType: keyof typeof combineHandlerMap) => {
        return existInAllList.reduce((acc, item) => {
            acc[item.id] = handleType
            return acc
        }, {} as Record<string, keyof typeof combineHandlerMap>)
    }

    // 设置所有数据的处理方式
    const setAllDataHandler = (handleType: keyof typeof combineHandlerMap) => {
        setCombineTypeData(getIdToHandlerMap(handleType))
    }

    // 设置初始数据
    useEffect(() => {
        setAllDataHandler('update')
    }, [existInAllList])

    return (
        <>
            <Table
                rowKey='id'
                size='mini'
                columns={[
                    {
                        title: '序号',
                        render: (_, __, index) => index + 1,
                    },
                    {
                        title: 'id',
                        dataIndex: 'id',
                        render: (row, record) => {
                            const oldItem = allListIdMap[record.id]
                            const newItem = itemsIdMap[record.id]
                            return (
                                <Popover
                                    content={
                                        <div className='flex overflow-auto max-h-[300px] gap-2'>
                                            <pre className='border-1 border-solid border-gray-300 p-2'>
                                                old:
                                                {JSON.stringify(
                                                    oldItem,
                                                    null,
                                                    2,
                                                )}
                                            </pre>
                                            <pre className='border-1 border-solid border-gray-300 p-2'>
                                                newImportedItem:
                                                {JSON.stringify(
                                                    newItem,
                                                    null,
                                                    2,
                                                )}
                                            </pre>
                                        </div>
                                    }
                                >
                                    {row}
                                </Popover>
                            )
                        },
                    },
                    {
                        title: '名称',
                        render: (_, record) => {
                            const oldName = allListIdMap[record.id]?.label
                            const newName = itemsIdMap[record.id]?.label
                            if (oldName === newName) {
                                return <div>{newName}</div>
                            }
                            return (
                                <div>
                                    <div>旧：{oldName}</div>
                                    <div>新：{newName}</div>
                                </div>
                            )
                        },
                    },
                    {
                        title: 'type',
                        render: (_, record) => {
                            const oldType = allListIdMap[record.id]?.type
                            const newType = itemsIdMap[record.id]?.type
                            if (oldType === newType) {
                                return <div>{newType}</div>
                            }
                            return (
                                <div>
                                    <div>旧：{oldType}</div>
                                    <div>新：{newType}</div>
                                </div>
                            )
                        },
                    },
                    {
                        title: (
                            <>
                                处理方式：
                                <Space>
                                    <Tooltip content='return assign({}, old, newImportedItem)，即新导入的数据覆盖原有的数据'>
                                        <Button
                                            size='mini'
                                            onClick={() => {
                                                setAllDataHandler('update')
                                            }}
                                        >
                                            {' '}
                                            更新
                                        </Button>
                                    </Tooltip>
                                    <Tooltip content='return newImportedItem，即新导入的数据覆盖原有的数据'>
                                        <Button
                                            size='mini'
                                            onClick={() => {
                                                setAllDataHandler('overwrite')
                                            }}
                                        >
                                            {' '}
                                            覆盖
                                        </Button>
                                    </Tooltip>
                                    <Tooltip content='return old，即保留原有的数据'>
                                        <Button
                                            size='mini'
                                            onClick={() => {
                                                setAllDataHandler('keep')
                                            }}
                                        >
                                            {' '}
                                            保留
                                        </Button>
                                    </Tooltip>
                                    <Tooltip content='return assign({}, newImportedItem, old)，即新导入的数据覆盖原有的数据'>
                                        <Button
                                            size='mini'
                                            onClick={() => {
                                                setAllDataHandler('updateNew')
                                            }}
                                        >
                                            {' '}
                                            更新新数据
                                        </Button>
                                    </Tooltip>
                                </Space>
                            </>
                        ),

                        render: (_, record) => {
                            return (
                                <Radio.Group
                                    value={combineTypeData[record.id]}
                                    onChange={(value) => {
                                        setCombineTypeData({
                                            ...combineTypeData,
                                            [record.id]: value,
                                        })
                                    }}
                                >
                                    <Radio value='update'>更新</Radio>
                                    <Radio value='overwrite'>覆盖</Radio>
                                    <Radio value='keep'>原数据</Radio>
                                    <Radio value='updateNew'>更新新数据</Radio>
                                </Radio.Group>
                            )
                        },
                    },
                ]}
                data={existInAllList}
            />
            <div className='flex justify-end gap-2 mt-4'>
                <Button onClick={handleCancel}>取消</Button>
                <Button type='primary' onClick={handleConfirm}>
                    确认
                </Button>
            </div>
        </>
    )
}

export const checkExistItems = async (items: IListItem[]) => {
    const itemsIdMap = keyBy(items, 'id')
    const allListIdMap: Record<string, IListItem> = {}
    const allList = await apiStore.getAllList()
    // 找出已经存在的项
    const existInAllList = allList.filter((item) => {
        allListIdMap[item.id] = item
        return !!itemsIdMap[item.id]
    })
    // 没有重复项，直接返回
    if (existInAllList.length === 0) {
        return items
    }
    // 有重复项，提示用户
    return new Promise<IListItem[]>((resolve, reject) => {
        const result = Modal.confirm({
            title: '以下项目重复',
            footer: null,
            style: {
                width: '80vw',
                minWidth: '500px',
            },
            content: (
                <DuplicateHandler
                    allListIdMap={allListIdMap}
                    itemsIdMap={itemsIdMap}
                    existInAllList={existInAllList}
                    onCancel={() => {
                        result.close()
                        reject()
                    }}
                    onConfirm={(items) => {
                        result.close()
                        resolve(items)
                    }}
                />
            ),
            onCancel: reject,
        })
    })
}
